<?php defined('SYSPATH') or die('No direct script access.');

/**
 *  uniapp相关配置
 */
class Controller_Uniapp  extends Stourweb_Controller
{
    public function before()
    {
        parent::before();
    }

    // 获取端设置
    protected function get_client()
    {
        $client = array(
            0 => '微信小程序',
            1 => 'UNIAPP H5'
        );
        if (St_Functions::is_normal_app_install('toutiao')) {
            $client[2] = '字节跳动小程序';
        }
        if (St_Functions::is_normal_app_install('zhifubao')) {
            $client[3] = '支付宝小程序';
        }
        return $client;
    }

    //  uniapp自定义导航
    public function action_custom_nav()
    {
        $action = $this->params['action'];
        if (empty($action)) {
            $this->display('stourtravel/uniapp/custom_nav');
        }
        else if ($action == 'read')
        {
            $node = Arr::get($_GET, 'node');
            $list = array();
            if ($node == 'root')//属性组根
            {
                $list = ORM::factory("uniapp_nav")->order_by(DB::expr("ifnull(m_displayorder, 9999) asc"))->get_all();
                foreach ($list as $k => $v)
                {
                    $list[$k]['leaf'] = true;
                    $list[$k]['allowDrag'] = false;
                    $list[$k] = $this->_get_menu_ico($v);
                    $list[$k]['m_client_str'] = self::_get_nav_client($v['m_client']);
                }
                $list[] = array(
                    'leaf' => true,
                    'id' => '0add',
                    'm_title' => '<button class="dest-add-btn df-add-btn" onclick="addSub(0)">添加</button>',
                    'allowDrag' => false,
                    'allowDrop' => false,
                    'm_displayorder' => 'add',
                    'm_isopen' => 'add'
                );
            }
            echo json_encode(array('success' => true, 'text' => '', 'children' => $list));
        }
        else if ($action == 'addsub')//添加子级
        {
            $nav_id = intval(Arr::get($_POST, 'nav_id'));
            $nav_name = Arr::get($_POST, 'nav_name');
            $litimg = Arr::get($_POST, 'litimg');
            $nav_mode = Arr::get($_POST, 'nav_mode');
            $nav_param = Arr::get($_POST, 'nav_param');
            $nav_path = Arr::get($_POST, 'nav_path');
            if($nav_id)
            {
                $model = ORM::factory("uniapp_nav", $nav_id);
            }
            else
            {
                $model = ORM::factory("uniapp_nav");
                $client = self::get_client();
                $model->m_client = implode(',', array_keys($client));
            }
            $model->m_title = $nav_name;
            //$model->m_mode = $nav_mode;
            $model->m_ico = $litimg;
            //$model->m_url = $nav_path;
            $model->m_params = $nav_param;
            $model->save();
            if ($model->saved()) {
                $model->reload();
                echo json_encode($model->as_array());
            }
        }
        else if ($action == 'save') //保存修改
        {
            $rawdata = file_get_contents('php://input');
            $field = Arr::get($_GET, 'field');
            $data = json_decode($rawdata);
            $id = $data->id;
            if ($field) {
                $model = ORM::factory("uniapp_nav", $id);
                if ($model->id) {
                    $model->$field = $data->$field;
                    $model->save();
                    if ($model->saved())
                        echo 'ok';
                    else
                        echo 'no';
                }
            }

        }
        else if ($action == 'delete')//属性删除
        {
            $rawdata = file_get_contents('php://input');
            $data = json_decode($rawdata);
            $id = $data->id;
            if (!is_numeric($id)) {
                echo json_encode(array('success' => false));
                exit;
            }
            $model = ORM::factory("uniapp_nav", $id);
            $model->delete();

        }
        else if ($action == 'update')//更新操作
        {
            $id = Arr::get($_POST, 'id');
            $field = Arr::get($_POST, 'field');
            $val = Arr::get($_POST, 'val');
            $model = ORM::factory("uniapp_nav", $id);
            if ($model->id) {
                $model->$field = $val;
                if ($field == 'm_displayorder') {
                    $val = intval($val) <= 0 ? 9999 : intval($val);
                    $model->$field = $val;
                }
                $model->save();
                if ($model->saved())
                    echo 'ok';
                else
                    echo 'no';
            }
        }
    }

    /**
     * 编辑uniapp导航显示端
     */
    public function action_dialog_set_xcx_client()
    {
        // 已保存的导航
        $navid = intval(Arr::get($_GET, 'navid'));
        $mode = intval(Arr::get($_GET, 'mode'))?:1;
        $info = array();
        if ($navid) {
            $info = DB::select()->from($mode==2?"uniapp_footmenu":"uniapp_nav")->where("id", "=", $navid)->execute()->current();
        }
        $new_arr = array();
        if($info['m_client'] == NULL){
            foreach (self::get_client() as $k=>$v){
                $new_arr[] = $k;
            }
        }else{
            $new_arr = explode(',', $info['m_client']);
        }
        $info['client_arr'] = $new_arr;
        $this->assign('client', self::get_client());
        $this->assign('info', $info);
        $this->display("stourtravel/uniapp/dialog_xcx_client");
    }

    /**
     * 保存uniapp显示端
     */
    public function action_save_client(){
        $id = intval(Arr::get($_POST, 'id'));
        $client = Arr::get($_POST, 'client');
        if($id){

        }else{
            echo 'no';
        }
    }

    /**
     * @param string $m_client 获取导航显示端的字符串
     * @return string
     */
    private function _get_nav_client($m_client)
    {
        $client = self::get_client();
        if($m_client == NULL){
            return implode('、', array_values($client));
        }else{
            $m_arr = explode(',', $m_client);
            $new_arr = array();
            foreach ($m_arr as $v){
                if(isset($client[$v])){
                    $new_arr[] = $client[$v];
                }
            }
            return implode('、', array_values($new_arr));
        }
    }

    /**
     * @function 获取菜单的图片
     * @param $menu
     * @return mixed
     */
    private function _get_menu_ico($menu)
    {
        if(!$menu['m_ico'])
        {
            $menu['m_ico'] = Common::get_menu_no_ico($menu['m_typeid']);
        }
        $menu['default_ico'] = Common::get_menu_no_ico($menu['m_typeid']);
        return $menu;
    }


    // uniapp设置导航
    public function action_dialog_set_xcx_nav()
    {
        // 微信小程序导航
        $xcx_page = Model_Uniapp_Nav::get_uniapp_page();
        // 已保存的导航
        $navid = intval(Arr::get($_GET, 'navid'));
        $info = array();
        if($navid)
        {
            $info = DB::select()->from("uniapp_nav")->where("id","=",$navid)->execute()->current();
        }

        // 小程序页面
        $_xcx_default_page = $xcx_page['default_page']; // 默认页面
        $_xcx_model_page = $xcx_page['model_page']; // 应用页面 需要判断是否有该应用
        $xcx_page = array();
        // 检查
        foreach ($_xcx_model_page as &$v)
        {
            // 检查是否有该应用
            $check_model = Model_Model::is_install_model($v['typeid']);
            if($check_model == 1)
            {
                array_push($xcx_page,$v);
            }
        }
        $xcx_page = array_merge($xcx_page,$_xcx_default_page);

        $this->assign("info",$info);
        $this->assign("xcx_page",$xcx_page);
        $this->display("stourtravel/uniapp/dialog_xcx_nav");
    }

    /*----------------------------------------*/
    /*           uniApp广告位设置               */
    /*----------------------------------------*/
    protected function get_ad_typename(){
        return array(
            1 => '产品',
            2 => 'UNI页面',
            3 => '自定义链接',
            4 => '三方小程序',
        );
    }

    /**
     * @function 广告位页面
     */
    public function action_ads_index(){
        $prefix = $this->params['prefix'];
        $data = include CACHE_DIR . 'newtravel/category.php';
        $kindname = '首页';
        foreach ($data['page'] as $item) {
            if ($prefix == "s_{$item['page_name']}") {
                $kindname =$item['name'];
                break;
            }
        }
        $models =  DB::select('id', 'modulename')->from('model')->where('isopen','=',1)->execute()->as_array();
        $this->assign('models', $models);
        $this->assign('kindname', $kindname);
        $this->assign('prefix', $prefix);
        $this->assign('client', $this->get_client());
        $this->assign('ads', DB::select()->from('advertise_5x')->where('id', '=', $this->params['id'])->execute()->current());
        $this->display('stourtravel/uniapp/clients');
    }

    /**
     * @function 设置导航和广告位链接
     */
    public function action_dialog_link()
    {
        // 微信小程序导航
        $xcx_page = Model_Uniapp_Nav::get_uniapp_page();
        // 小程序页面
        $_xcx_default_page = $xcx_page['default_page']; // 默认页面
        $_xcx_model_page = $xcx_page['model_page']; // 应用页面 需要判断是否有该应用
        $xcx_page = array();
        // 检查是否有该应用
        foreach ($_xcx_model_page as &$v) {
            $check_model = Model_Model::is_install_model($v['typeid']);
            if ($check_model == 1) {
                array_push($xcx_page, $v);
            }
        }
        $tongyong_link = self::tongyong_link();
        $xcx_page = array_merge($xcx_page,$_xcx_default_page,$tongyong_link);

        // 开启的模块
        $models =  DB::select('id', 'modulename')->from('model')->where('isopen','=',1)->and_where('is_orderable','=',1)->execute()->as_array();

        $this->assign('models', $models);
        $this->assign("xcx_page",$xcx_page);
        $this->display("stourtravel/uniapp/dialog_link");
    }

    /**
     * @function 获取指定类型产品
     */
    public function  action_get_product()
    {
        $action = $this->params['action'];
        if ($action == 'read') {
            // 获取线路 酒店 驻车 门票 中的第一个应用(防止应用没有)
            $models =  DB::select('id', 'modulename')
                ->from('model')->where('isopen','=',1)
                ->where('id','not in',[10,12,14,101,106,107,111,115])
                ->execute()
                ->as_array();
            $typeid = Arr::get($_GET, 'typeid') ? Arr::get($_GET, 'typeid') : $models[0]['id'];
            $modeldata = DB::select('maintable', 'modulename')->from('model')->where('id', '=', $typeid)->execute()->current();
            $protable = $modeldata['maintable'];
            $start = Arr::get($_GET, 'start');
            $limit = Arr::get($_GET, 'limit');
            $keyword = Arr::get($_GET, 'keyword');
            $w = "a.id is not null and ishidden=0 ";
            if ($protable == 'model_archive') {
                $w .= " and a.typeid=$typeid";
            }
            $w .= empty($keyword) ? '' : " and a.title like '%{$keyword}%'";
            $totalcount_arr = DB::query(Database::SELECT, "select count(*) as num from sline_$protable a where $w")->execute()->as_array();
            $sql = "select a.id,a.title,a.litpic from sline_$protable as a   LEFT JOIN  sline_allorderlist as b   ON (a.id=b.aid and b.typeid=$typeid) where $w    ORDER BY IFNULL(b.displayorder,9999) ASC,a.modtime DESC,a.addtime DESC  limit $start,$limit";
            $list = DB::query(Database::SELECT, $sql)->execute()->as_array();
            foreach ($list as &$l) {
                $l['typename'] = $modeldata['modulename'];
                $l['typeid'] = $typeid;
                $l['bh'] = St_Product::product_series($l['id'], "{$typeid}"); //编号
            }
            $result['total'] = $totalcount_arr[0]['num'];
            $result['lists'] = $list;
            $result['success'] = true;
            echo json_encode($result);
        }
    }

    /**
     * @function 添加广告
     */
    public function action_add_ads()
    {
        $adType = intval(Arr::get($_POST, 'adType'));
        $linkData = Arr::get($_POST, 'linkData');
        $prefix = Common::remove_xss(Arr::get($_POST, 'prefix'));
        $number = intval(Arr::get($_POST, 'number', 1));
        $custom_label = Arr::get($_POST, 'custom_label', '');

        $result = array(
            'status' => false
        );
        // 广告类型
        if (!in_array($adType, array(1, 2, 3, 4))) {
            $result['msg'] = '不支持的广告类型';
            exit(json_encode($result));
        }
        // 广告数据
        $linkData = json_decode($linkData, true);
        if (!$linkData) {
            $result['msg'] = '广告数据有误';
            exit(json_encode($result));
        }

        // 保存数据
        $baseData = array(
            'number' => $number,
            'prefix' => $prefix,
            'adtype' => $adType,
            'custom_label' => $custom_label,
        );
        if ($adType == 1) {
            // 产品类型
            foreach ($linkData as $v) {
                $upData = $baseData;
                $upData['proid'] = $v['id'];
                $upData['typeid'] = $v['typeid'];
                $upData['protitle'] = $v['title'];
                $upData['adname'] = $v['title'];
                $upData['addis'] = mb_substr($v['dis'], 0, 120);
                $upData['adsrc'] = $v['litpic'];
                DB::insert('xcx_ads', array_keys($upData))->values(array_values($upData))->execute();
            }
            $result['status'] = true;
            $result['msg'] = '保存成功';
            exit(json_encode($result));
        } elseif ($adType == 2) {
            // uni-page
            foreach ($linkData as $v) {
                $upData = $baseData;
                $upData['adname'] = $v['title'];
                $upData['adlink'] = $v['path'];
                $upData['addis'] = mb_substr($v['dis'], 0, 120);
                DB::insert('xcx_ads', array_keys($upData))->values(array_values($upData))->execute();
            }
            $result['status'] = true;
            $result['msg'] = '保存成功';
            exit(json_encode($result));
        } elseif ($adType == 3) {
            // 自定义链接
            $upData = $baseData;
            $upData['adname'] = $linkData['title'];
            $upData['adlink'] = $linkData['path'];
            $upData['addis'] = mb_substr($linkData['dis'], 0, 120);
        } else {
            // 三方小程序
            $upData = $baseData;
            $upData['adname'] = $linkData['appId'];
            $upData['addis'] = mb_substr($linkData['dis'], 0, 120);
            $upData['adlink'] = $linkData['appId'] . '||' . $linkData['path'];
        }
        DB::insert('xcx_ads', array_keys($upData))->values(array_values($upData))->execute();
        $result['status'] = true;
        $result['msg'] = '保存成功';
        exit(json_encode($result));
    }

    // 获取广告列表
    public function action_get_ads_list(){
        $page = intval(Arr::get($_POST, 'page', 1));
        $prefix = Arr::get($_POST, 'prefix');
        $number = Arr::get($_POST, 'number', 1);
        $custom_label = Arr::get($_POST, 'custom_label', '');
        $limit = 10;
        $start = ($page - 1) * $limit;
        $model = DB::select()
            ->from('xcx_ads')
            ->where('prefix', '=', $prefix)
            ->where('number', '=', $number);
        if($custom_label) {
            $model->where('custom_label', '=', $custom_label);
        }else{
            $model->where('custom_label', '=', '');
        }
        $total = $model->execute()->count();
        $list = $model->order_by('id', 'desc')
            ->offset($start)
            ->limit($limit)
            ->execute()
            ->as_array();
        $clintNo = self::get_ad_typename();
        foreach ($list as &$v){
            $v['adTypeName'] = isset($clintNo[$v['adtype']]) ? $clintNo[$v['adtype']] : '--';
            // 小程序类型广告位
            if($v['adtype'] == 4) {
                $pathArr = explode('||',$v['adlink']);
                $v['appId'] = isset($pathArr[0]) ? $pathArr[0] :  '';
                $v['appPath'] = isset($pathArr[1]) ? $pathArr[1] : '';
            }
        }
        $result = array(
            'status' => true,
            'data' => array(
                'total' => $total,
                'page' => $page,
                'pagesize' => $limit,
                'list' => $list,
            )
        );
        echo json_encode($result);
    }

    /**
     * @function 删除广告
     */
    public function action_del_ads(){
        $id = Arr::get($_POST, 'id');
        if (is_numeric($id)) {
            DB::delete('xcx_ads')->where('id', '=', $id)->execute();
        }
        $result = array(
            'status' => true,
            'msg' => ''
        );
        echo json_encode($result);
    }

    /**
     * @function 更新广告字段的
     */
    public function action_update_ads_field ()
    {
        $id = intval(Arr::get($_POST, 'id'));
        $field = Arr::get($_POST, 'field');
        $val = Common::remove_xss(Arr::get($_POST, 'val'));

        $result = array(
            'status' => false
        );
        if(!$id){
            $result['msg'] = '参数错误';
            exit(json_encode($result));
        }
        // 字段类型
        if (!in_array($field, array('displayorder', 'client_no', 'adname', 'adsrc'))) {
            $result['msg'] = '不支持的参数';
            exit(json_encode($result));
        }

        if ($field == 'displayorder') {
            $val =  !empty($val) ?  $val : 9999;
        }
        DB::update('xcx_ads')->where("id=$id")->set(array($field => $val))->execute();
        $result = array(
            'status' => true,
            'msg' => '保存成功'
        );
        exit(json_encode($result));
    }


    /*----------------------------------------*/
    /*           手机导航配置操作部分            */
    /*----------------------------------------*/
    public function action_model_nav()
    {
        $action = $this->params['action'];

        if (empty($action)) {
            $this->display('stourtravel/uniapp/model_nav');
        } else if ($action == 'read') {

            $node = Arr::get($_GET, 'node');

            $list = array();
            if ($node == 'root')//属性组根
            {


                $list = ORM::factory("m_nav")->where("m_issystem","=",1)->order_by(DB::expr("ifnull(m_displayorder, 9999) asc"))->get_all();
                foreach ($list as $k => &$v) {
                    $list[$k]['channel_name'] = Model_Model::get_module_name($v['m_typeid']);
                    $list[$k]['leaf'] = true;
                    $list[$k]['allowDrag'] = false;
                    $list[$k] = $this->_get_menu_ico($v);

                }
//                $list[] = array(
//                    'leaf' => true,
//                    'id' => '0add',
//                    'm_title' => '<button class="dest-add-btn df-add-btn" onclick="addSub(0)">添加</button>',
//                    'channel_name' => '',
//                    'allowDrag' => false,
//                    'allowDrop' => false,
//                    'm_displayorder' => 'add',
//                    'm_isopen' => 'add'
//                );
            }
            echo json_encode(array('success' => true, 'text' => '', 'children' => $list));
        } else if ($action == 'addsub')//添加子级
        {
            $pid = Arr::get($_POST, 'pid');
            $model = ORM::factory("m_nav");
            $model->m_title = "未命名";
            $model->m_url = '';
            $model->save();

            if ($model->saved()) {
                $model->reload();
                echo json_encode($model->as_array());
            }
        } else if ($action == 'save') //保存修改
        {
            $rawdata = file_get_contents('php://input');
            $field = Arr::get($_GET, 'field');
            $data = json_decode($rawdata);
            $id = $data->id;
            if ($field) {
                $model = ORM::factory("m_nav", $id);
                if ($model->id) {
                    $model->$field = $data->$field;
                    $model->save();
                    if ($model->saved())
                        echo 'ok';
                    else
                        echo 'no';
                }
            }

        } else if ($action == 'delete')//属性删除
        {
            $rawdata = file_get_contents('php://input');
            $data = json_decode($rawdata);
            $id = $data->id;
            if (!is_numeric($id)) {
                echo json_encode(array('success' => false));
                exit;
            }
            $model = ORM::factory("m_nav", $id);
            $model->delete();

        } else if ($action == 'update')//更新操作
        {
            $id = Arr::get($_POST, 'id');
            $field = Arr::get($_POST, 'field');
            $val = Arr::get($_POST, 'val');
            $model = ORM::factory("m_nav", $id);
            if ($model->id) {
                $model->$field = $val;
                if ($field == 'm_displayorder') {
                    $val = intval($val) <= 0 ? 9999 : intval($val);
                    $model->$field = $val;
                }
                $model->save();
                if ($model->saved())
                    echo 'ok';
                else
                    echo 'no';
            }
        }

    }

    /**
     * @function uniapp主导航链接设置
     */
    public function action_dialog_nav_link()
    {
        // 微信小程序导航
        $xcx_page = Model_Uniapp_Nav::get_uniapp_page();
        $navid = $_GET['navid'];
        $mode = $_GET['mode'];//2是底部导航;
        // 小程序页面
        $_xcx_default_page = $xcx_page['default_page']; // 默认页面
        $_xcx_model_page = $xcx_page['model_page']; // 应用页面 需要判断是否有该应用
        $xcx_page = array();
        // 检查是否有该应用
        foreach ($_xcx_model_page as &$v) {
            $check_model = Model_Model::is_install_model($v['typeid']);
            if ($check_model == 1) {
                array_push($xcx_page, $v);
            }
        }
        $tongyong_link = self::tongyong_link();
        $xcx_page = array_merge($xcx_page,$_xcx_default_page,$tongyong_link);

      // var_dump($xcx_page);exit;
        // 开启的模块
        $models =  DB::select('id', 'modulename')->from('model')->where('isopen','=',1)->and_where('is_orderable','=',1)->execute()->as_array();
        $this->assign('navid',$navid);
        $this->assign('models', $models);
        $this->assign("xcx_page",$xcx_page);
        $this->assign("mode",$mode);
        $this->display("stourtravel/uniapp/dialog_nav_link");
    }

    public function tongyong_link()
    {
        $arr = array(
            "subname" => "",
            "type" => 2,
            "typeid" => '',
            "title" => "通用",
            "page" => array(
                array(
                    "path" => "/subPackages/tongyong/list", // 路径
                    "params" => "keyword", // 参数
                    "title" => "列表页",
                    "dis" => "列表页【keyword：搜索关键词】"
                )
            )
        );
        $data = array();
        $tongyong_info = DB::select()->from("model")->where("maintable='model_archive'")->execute()->as_array();
        foreach($tongyong_info as $v){
            $arr['subname'] = "tongyong_".$v['pinyin'];
            $arr['typeid'] = $v['id'];
            $arr['title'] = $v['modulename'];
            array_push($data,$arr);
        }

        return $data;
    }

    /**
     * @function 保存主导航链接
     */
    public function action_save_link()
    {
        $data = json_decode($_POST['data'],true);
        $params = $data['data'][0];
        $params = $params?$params:$data['data'];
        $status = DB::select()->from('uniapp_nav')->where("id={$params['navid']}")->execute()->current();
        if($data['adType']==1){
            $pinyin = false;
            if($params['typeid']){
                $pinyin = DB::select()->from('model')->where("id={$params['typeid']}")->execute()->get('pinyin');
            }
            $arr = array(
                'm_typeid' => $params['typeid'],
                'type' => $data['adType'],
                'product_id' => $params['id'],
                'm_mode' => $pinyin?'system_'.$pinyin:null,
                'm_url' => ''
            );
            if($status){
                $res = DB::update('uniapp_nav')->where("id={$params['navid']}")->set($arr)->execute();
            }else{
                $res = DB::insert('uniapp_nav', array_keys($arr))->values(array_values($arr))->execute();
            }
        }else{
			if($data['adType']==4){
				$params['path'] = $params['appId'].'||'.$params['path'];
			}
			if($data['adType']==3){
				$params['path'] = $params['path'];
			}
            $arr = array(
                'type' => $data['adType'],
                'm_url' => $params['path'],
                'm_typeid' => $params['typeid']?$params['typeid']:null,
                'product_id' => null,
                'm_mode' => $params['subname']?$params['subname']:null,
                'is_nested'=>$params['is_nested']
            );
            if($status){
                $res = DB::update('uniapp_nav')->where("id={$params['navid']}")->set($arr)->execute();
            }else{
                $res = DB::insert('uniapp_nav', array_keys($arr))->values(array_values($arr))->execute();
            }
        }

        echo 1;
    }


    //底部菜单列表
    public function action_footmenu(){
        $action = $this->params['action'];
        if (empty($action)) {
            $this->display('stourtravel/uniapp/footmenu');
        }
        else if ($action == 'read')
        {
            $node = Arr::get($_GET, 'node');
            $list = array();
            if ($node == 'root'){
                $list = ORM::factory("uniapp_footmenu")
                    ->order_by(DB::expr("ifnull(m_displayorder, 9999) asc"))
                    ->get_all();
                foreach ($list as $k => $v) {
                    if($v['type']==1){//产品
                        $list[$k]['m_url']=St_Functions::table_field($v['m_typeid'])[7];
                    }elseif ($v['type']==5){
                        $list[$k]['m_url']='电话';
                    }elseif ($v['type']==6){
                        $list[$k]['m_url']='企业微信';
                    }
                    $list[$k]['leaf'] = true;
                    $list[$k]['allowDrag'] = false;
                    $list[$k]['is_system'] = $list[$k]['is_system']==1?'系统自带':"用户自定义";
                    $list[$k]['m_client_str'] = self::_get_nav_client($v['m_client']);
                }
                $list[] = array(
                    'leaf' => true,
                    'id' => '0add',
                    'm_title' => '<button class="dest-add-btn df-add-btn" onclick="addSub(0)">添加</button>',
                    'allowDrag' => false,
                    'allowDrop' => false,
                    'm_displayorder' => 'add',
                    'm_isopen' => 'add'
                );
            }
            echo json_encode(array('success' => true, 'text' => '', 'children' => $list));
        }
        else if ($action == 'addsub')//添加子级
        {
            $id = intval(Arr::get($_POST, 'id'));
            $m_title = Arr::get($_POST, 'm_title');
            $m_ico1 = Arr::get($_POST, 'm_ico1');
            $m_ico2 = Arr::get($_POST, 'm_ico2');
            $font_color1 = Arr::get($_POST, 'font_color1');
            $font_color2 = Arr::get($_POST, 'font_color2');
            $nav_param = Arr::get($_POST, 'nav_param');
            if($id) {
                $model = ORM::factory("uniapp_footmenu", $id);
            } else {
                $model = ORM::factory("uniapp_footmenu");
                $client = self::get_client();
                $model->m_client = implode(',', array_keys($client));
            }
            $model->m_title = $m_title;
            $model->m_ico1 = $m_ico1;
            $model->m_ico2 = $m_ico2;
            $model->font_color1 = $font_color1;
            $model->font_color2 = $font_color2;
            $model->m_params = $nav_param;
            $model->is_system = 0;
            $model->save();
            if ($model->saved()) {
                $model->reload();
                echo json_encode($model->as_array());
            }
        }
        else if ($action == 'save') //保存修改
        {
            $rawdata = file_get_contents('php://input');
            $field = Arr::get($_GET, 'field');
            $data = json_decode($rawdata);
            $id = $data->id;
            if ($field) {
                $model = ORM::factory("uniapp_footmenu", $id);
                if ($model->id) {
                    $model->$field = $data->$field;
                    $model->save();
                    if ($model->saved())
                        echo 'ok';
                    else
                        echo 'no';
                }
            }

        }
        else if ($action == 'delete')//属性删除
        {
            $rawdata = file_get_contents('php://input');
            $data = json_decode($rawdata);
            $id = $data->id;
            if (!is_numeric($id)) {
                echo json_encode(array('success' => false));
                exit;
            }
            $model = ORM::factory("uniapp_footmenu", $id);
            $model->delete();

        }
        else if ($action == 'update')//更新操作
        {
            $id = Arr::get($_POST, 'id');
            $field = Arr::get($_POST, 'field');
            $val = Arr::get($_POST, 'val');
            $model = ORM::factory("uniapp_footmenu", $id);
            if ($model->id) {
                $model->$field = $val;
                if ($field == 'm_displayorder') {
                    $val = intval($val) <= 0 ? 9999 : intval($val);
                    $model->$field = $val;
                }
                $model->save();
                if ($model->saved())
                    echo 'ok';
                else
                    echo 'no';
            }
        }
    }

    //设置footmenu弹窗
    public function action_dialog_set_footmenu(){
        // 微信小程序导航
        $xcx_page = Model_Uniapp_Footmenu::get_uniapp_page();
        // 已保存的导航
        $navid = intval(Arr::get($_GET, 'navid'));
        $info = array();
        if($navid) {
            $info = DB::select()->from("uniapp_footmenu")->where("id","=",$navid)->execute()->current();
        }
        // 小程序页面
        $_xcx_default_page = $xcx_page['default_page']; // 默认页面
        $_xcx_model_page = $xcx_page['model_page']; // 应用页面 需要判断是否有该应用
        $xcx_page = array();
        // 检查
        foreach ($_xcx_model_page as &$v)
        {
            // 检查是否有该应用
            $check_model = Model_Model::is_install_model($v['typeid']);
            if($check_model == 1)
            {
                array_push($xcx_page,$v);
            }
        }
        $xcx_page = array_merge($xcx_page,$_xcx_default_page);
        $this->assign("info",$info);
        $this->assign("xcx_page",$xcx_page);
        $this->display("stourtravel/uniapp/dialog_set_footmenu");
    }

    //保存底部导航
    public function action_save_footmenu(){
        $data = json_decode($_POST['data'],true);
        $params = $data['data'][0];
        $params = $params?$params:$data['data'];
        $status = DB::select()->from('uniapp_footmenu')->where("id={$params['navid']}")->execute()->current();
        if($data['adType']==1){//跳产品
            $pinyin = false;
            if($params['typeid']){
                $pinyin = DB::select()->from('model')->where("id={$params['typeid']}")->execute()->get('pinyin');
            }
            $arr = array(
                'm_typeid' => $params['typeid'],
                'type' => $data['adType'],
                'product_id' => $params['id'],
                'm_mode' => $pinyin?'system_'.$pinyin:null,
                'm_url' => ''
            );
            if($status){
                $res = DB::update('uniapp_footmenu')->where("id={$params['navid']}")->set($arr)->execute();
            }else{
                $res = DB::insert('uniapp_footmenu', array_keys($arr))->values(array_values($arr))->execute();
            }
        }else{
            if($data['adType']==4){
                $params['path'] = $params['appId'].'||'.$params['path'];
            }
            if($data['adType']==3){
                $params['path'] = $params['path'];
            }
            $arr = array(
                'type' => $data['adType'],
                'm_url' => $params['path'],
                'm_typeid' => $params['typeid']?$params['typeid']:null,
                'product_id' => null,
                'm_mode' => $params['subname']?$params['subname']:null,
                'is_nested'=>$params['is_nested']
            );
            if($status){
                $res = DB::update('uniapp_footmenu')->where("id={$params['navid']}")->set($arr)->execute();
            }else{
                $res = DB::insert('uniapp_footmenu', array_keys($arr))->values(array_values($arr))->execute();
            }
        }
        echo 1;
    }

}